// index.js
const app = getApp();

Page({
  data: {
    temperature: 25,
    humidity: 50,
    heaterStatus: false,
    password: ['', '', '', ''],
    isProcessing: false,
    connectButtonText: '连接服务器',
    status:'',
  },

  onLoad() {
    // 注册页面到app.js
    app.registerPage(this);
    // 初始化数据
    this.setData({
      temperature: app.globalData.temperature,
      humidity: app.globalData.humidity,
      heaterStatus: app.globalData.heaterStatus,
      status:app.globalData.status,
      password:app.globalData.password,
      id:app.globalData.id,
      connectButtonText: this.getConnectButtonText(app.globalData.mqttStatus)
    });
    //
    this.loadCurrentState();
    const savedState = wx.getStorageSync('indexState');
    if (savedState) {
      this.setData({
        password: savedState.password || this.data.password,
        doorStatus: savedState.doorStatus,
        heaterStatus: savedState.heaterStatus,
        currentPassword: savedState.currentPassword || '0000'
      });
    }
    // 监听全局设备状态变化
    const currentState = app.getCurrentState();
    this.setData({
      doorStatus: currentState.isDoorOpened,
      heaterStatus: currentState.isHeated,
      currentPassword: currentState.newPassword
    });

  },

  onUnload() {
    // 注销页面
    app.unregisterPage(this);
    this.saveCurrentState();

  },

  onShow() {
    // 从后台唤醒时检查连接
    if (app.globalData.mqttStatus === 'disconnected') {
      this.connectToMqtt(this.globalData.mqttHost);
    };
    this.loadCurrentState();
    app.initUserRole(app.globalData.userRoles.user)
  },

  onHide() {
    // 进入后台时清理心跳
    if (this._heartbeatTimer) clearInterval(this._heartbeatTimer);
    this.saveCurrentState();
  },

  // 更新数据的方法，由app.js调用
  updateData(data) {
    this.setData(data);
  },

  getConnectButtonText(status) {
    switch(status) {
      case 'connected': return '已连接';
      case 'connecting': return '连接中...';
      case 'disconnected': return '连接服务器';
      default: return '连接服务器';
    }
  },
  // 保存状态到本地存储
  saveCurrentState() {
    wx.setStorageSync('indexState', {
      password: this.data.password,
      doorStatus: this.data.doorStatus,
      heaterStatus: this.data.heaterStatus,
      currentPassword: this.data.currentPassword
    });
  },
  //
  loadCurrentState() {
    const state = app.getCurrentState();
    this.setData({
      heaterStatus: state.isHeated,
      doorStatus: state.isDoorOpened,
      currentPassword: state.newPassword
    });
  },
  //
  checkProcessing() {
    if (this.data.isProcessing) {
      wx.showToast({ title: '请等待当前操作完成', icon: 'none' });
      return true;
    }
    this.setData({ isProcessing: true });
    return false;
  },

  toggleDoor() {
    if (this.checkProcessing()) return;
    if (this.data.status !== 'B') return;
    
    const success = app.sendCommand({ door: "33" });
    if (success) {
      wx.showToast({ title: '正在开门...', icon: 'loading' });
      app.updateDeviceState({ isDoorOpened: true });
    }
    setTimeout(() => this.setData({ isProcessing: false }), 5000);
  },

  toggleHeater() {
    if (this.checkProcessing()) return;
    if (this.data.status !== 'B') return;

    const newStatus = !this.data.heaterStatus;
    app.updateDeviceState({ isHeated: newStatus });
    this.setData({ heaterStatus: newStatus });
    const success = app.sendCommand({ heater: newStatus ? 123 : 234 });
    if (!success) {
      this.setData({ heaterStatus: !newStatus });
    }
    setTimeout(() => this.setData({ isProcessing: false }), 5000);
  },
  showPassPassword() {
    if (this.data.status !== 'B') return;

    const password = this.data.password;
    // 检查当前密码是否有效
    if (Array.isArray(password) && 
        password.length === 4 && 
        password.every(c => String(c).trim() !== '')) {
      // 显示当前密码并更新应用状态
      wx.showModal({
        title: '当前取餐密码',
        content: password.join(''),
        showCancel: false,
        confirmText: '知道了',
        confirmColor: '#07c160'
      });
    } else {
        // 无任何可用密码时提示
        wx.showToast({
          title: '尚未收到密码',
          icon: 'none',
          duration: 2000
        });
      }
    },


    gotonext()
    {
      wx.navigateTo({
        url: '/pages/pass/index'
      }) 
    }

});